WWL.graph = function ( name, options )
{
	var graph_types = [
		'AccumulatorBar',
		'Area',
		'Bar',
		'Dot',
		'Line',
		'Mini.Bar',
		'Mini.Pie',
		'Mini.SideBar',
		'Net',
		'Pie',
		'SideBar',
		'SideStackedBar',
		'Spider',
		'StackedArea',
		'StackedBar'
	];

	var graph = new WWL ( 'graph', name );

	graph.container = $( graph.name );
	
	if ( graph.container.firstChild && graph.container.firstChild.tagName == 'CANVAS' )
	{
		graph.canvas = graph.container.firstChild;
		if ( ! graph.canvas.id )
		{
			var i = 1;
			while ( $( 'graph-canvas-' + i ) )
				i++;
			graph.canvas.id = 'graph-canvas-' + i;
		}
	}
	else
	{
		graph.canvas = document.createElement ( 'canvas' );
		graph.canvas.id = 'graph-' + graph.name;
		graph.container.appendChild ( graph.canvas );
	}

	graph.draw = function ( params )
	{
		if ( ! params )
		{
			console.error ( 'Graph error: no parameters supplied!' );
			return;
		}

		if ( ! params.type || graph_types.indexOf ( params.type ) == -1 )
		{
			console.error ( 'Graph error: invalid graph type: %s', params.type );
			return null;
		}

		if ( params.width ) this.width = parseInt ( params.width, 10 );
		if ( params.height ) this.height = parseInt ( params.height, 10 );
		var size = liwe.dom.get_size ( this.container );
		if ( ! this.width ) this.width = size [ 0 ];
		if ( ! this.height ) this.height = size [ 1 ];

		this.bluff = new Bluff [ params.type ] ( this.canvas.id, String.format ( "%dx%d", this.width, this.height ) );

		if ( params.theme && this [ 'theme_' + params.theme ] ) this.bluff [ 'theme_' + params.theme ] ();

		if ( ! params.data )
		{
			console.error ( 'Graph error: no data supplied!' );
			return;
		}

		var self = this;
		params.data.iterate ( function ( v, k )
		{
			self.bluff.data ( k, v );
		} );

		if ( params.options )
		{
			params.options.iterate ( function ( v, k )
			{
				self.bluff [ k ] = v;
			} );
		}

		if ( params.theme ) this.bluff [ 'theme_' + params.theme ] ();

		this.bluff.draw ();
	};

	return graph;
};

WWL.graph.get_instance = function ( instance_name )
{
	return WWL.get_instance ( 'graph', instance_name );
};

